library(jsonlite)
library(dplyr)
library(foreign)
library(maptools)
library(foreign)
library(classInt)
library(RColorBrewer)
library(ggplot2)
library(plyr)
library(lsr)
library(bear)
library(MASS)
library(sandwich)
library(plm)
library(ggmap)
library(rgeos)
library(rgdal)
#library(sf)

# MAPS VOTE #


communes=readShapePoly("COMMUNE.SHP")
communes_obf=read.dbf("COMMUNE.DBF")
regions=readShapePoly("nouvelles_regions.shp")
data=read.dta("Data_for_Maps_clean.dta")

communes_obf_data=merge(communes_obf,data, by.x="INSEE_COM", by.y="com", all.x=T)
communes_obf_data=communes_obf_data[order(communes_obf_data$ID_GEOFLA),]

# Vote LE PEN 2012
nclr=9
plotclr <- brewer.pal(9, "Purples")
plotvar <- communes_obf_data$fn_t1
class <- classIntervals(plotvar,nclr,style = "quantile",dataPrecision=2)
colcode <- findColours(class, plotclr)
jpeg(filename="Figure3a.jpg")
plot(communes, col=colcode, border="#00000000", add=F)
plot(regions, col="#00000000", border="black", add=T)
legend("bottomleft", legend = names(attr(colcode, "table")), border="#00000000", bty="n",  title = "Vote Le Pen (2012 - Round1)",fill = attr(colcode, "palette"),cex = 0.6)
dev.off()


# Vote LE PEN 2017

# Apply the values of 2017 to the deciles of 2012
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017<12.95,plotclr[1],"")
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017>=12.95 & communes_obf_data$voix_fn_t1_2017<15.69  ,plotclr[2],colcode3)
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017>=15.69 & communes_obf_data$voix_fn_t1_2017<17.98  ,plotclr[3],colcode3)
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017>=17.98 & communes_obf_data$voix_fn_t1_2017<20  ,plotclr[4],colcode3)
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017>=20 & communes_obf_data$voix_fn_t1_2017<22.06  ,plotclr[5],colcode3)
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017>=22.06 & communes_obf_data$voix_fn_t1_2017<24.15  ,plotclr[6],colcode3)
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017>=24.15  & communes_obf_data$voix_fn_t1_2017<26.62  ,plotclr[7],colcode3)
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017>=26.62  & communes_obf_data$voix_fn_t1_2017<30  ,plotclr[8],colcode3)
colcode3=ifelse(communes_obf_data$voix_fn_t1_2017>=30  ,plotclr[9],colcode3)


jpeg(filename="Figure3b.jpg")
plot(communes, col=colcode3, border="#00000000", add=F)
plot(regions, col="#00000000", border="black", add=T)
legend("bottomleft", legend = names(attr(colcode, "table")), border="#00000000", bty="n",  title = "Vote Le Pen (2017 - Round1)",fill = attr(colcode, "palette"),cex = 0.6)
dev.off()

